# 获得整个rule_flatten表
import json
import pandas as pd
import os
import sys
from sqlalchemy import create_engine, text

# 添加父目录到路径，以便导入config和common模块
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from config import create_db_engine
from common.rule_flatten_handle import flatten_json, unflatten_json

# 创建数据库引擎
engine = create_db_engine()

# 将 rule_flatten 表中全部数据读出来，然后unflatten成 JSON，保存到 ruleData_all.json
def rule_unflatten_from_orcl():
    print("Fetching all rules from rule_flatten table...")
    with engine.connect() as conn:
        sql = text("SELECT * FROM rule_flatten")
        result = conn.execute(sql)
        rows = result.fetchall()
        columns = result.keys()
        df = pd.DataFrame(rows, columns=columns)

    # 将 DataFrame 转换为字典列表
    records = df.to_dict(orient='records')

    # 对每一行数据进行 unflatten 操作
    print("Unflattening records...")
    all_rules = unflatten_json(records)

    # 保存到 JSON 文件
    print("Saving all rules to ruleData_all.json...")
    with open('ruleData_all.json', 'w', encoding='utf-8') as f:
        json.dump(all_rules, f, ensure_ascii=False, indent=4)
    
    print("All rules have been saved to ruleData_all.json.")
    return all_rules

if __name__ == "__main__":
    rule_unflatten_from_orcl()
